<?php

namespace App\Http\Controllers;

use App\Models\ActivityList;
use App\Models\Form\ActivityForm;
use App\Models\Form\LoginForm;
use App\Models\UserList;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ActivityController extends Controller
{
    private function rj($success, $code, $msg, $data)
    {
        return response()->json(
            compact('success', 'code', 'msg', 'data')
        );
    }

    //
    public function reg(Request $request)
    {
        $result = Validator::make($request->json()->all(), [
            'name' => 'required|max:255',
            'sex' => 'required|digits_between:0,2',
            'mobile' => 'required|unique:userlist|max:30',
            'address' => 'required|max:255',
            'province' => 'required|max:255',
            'city' => 'required|max:255',
            'county' => 'required|max:255',
            'area' => 'required|max:255',
            'school' => 'required|max:255',
        ]);
        if ($result->fails()) {
            return $result->errors();
        }
        $dbData = $result->validated();
        $user = new UserList();
        foreach ($dbData as $k => $v) {
            $user[$k] = $v;
        }
        $state = $user->save();
        return $this->rj($state, $state ? 0 : -1, $state ? 'pass' : 'error', $state);
    }

    public function login(Request $request)
    {
        $login = new LoginForm($request->json()->all());
        if ($login->isValid()) {
            return $this->rj(true, 0, 'pass', $login);
        } else {
            return $this->rj(false, -1, 'error', $login->getErrors());
        }
    }

    public function newActivity(Request $request)
    {
        $activity = new ActivityForm($request->json()->all());
        if ($activity->isValid()) {
            $v = ActivityList::create(
                $activity->getDBData()
            );
            if ($v) {
                return $this->rj(true, 0, 'pass', $activity);
            } else {
                return $this->rj(false, -1, '创建对象失败', $v);
            }
        } else {
            return $this->rj(false, -1, 'error', $activity->getErrors());
        }
    }

    public function errorShow($msg)
    {
        return $this->rj(false, -1, $msg, null);
    }
}
